import hashlib
import json
import uuid

import cv2
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect

from ocr.yolo_ocr import predict_model
from onlineocr import settings
from login import forms as login_forms
from login import models as login_models
import os


# Create your views here.
# 加密

def check_login(func):
    """
    查看session值用来判断用户是否已经登录
    :param func:
    :return:
    """

    def warpper(request, *args, **kwargs):
        if request.session.get('is_login', False):
            return func(request, *args, **kwargs)
        else:
            return redirect('/login/')

    return warpper


def hash_code(s, salt='sanfen'):  # s+salt一起进行加密
    h = hashlib.sha256()
    s = s + salt
    h.update(s.encode())  # upadte 只接受bytes类型
    return h.hexdigest()


@check_login
def index(request):
    if request.method == 'POST':
        image_form = login_forms.UploadImageForm(request.POST, request.FILES)
        message = request.FILES
        if image_form.is_valid():
            username = request.session['user_name']
            try:
                image = image_form.cleaned_data['image']
                img = login_models.Image.objects.create(image=image, user_name=username, content='')
                uuid_code = ''.join(str(uuid.uuid1()).split('-'))
                img.uuid = uuid_code
                img.save()

                res = predict_model(cv2.imread(img.image.path))
                alert_image = login_models.Image.objects.get(uuid=uuid_code)
                alert_image.content = json.dumps(res)
                alert_image.save()

                message_index = '上传成功！'
                return redirect('/result/%s' % alert_image.uuid)
            except Exception as e:
                print(e)
                message_index = '请求异常！'
                return render(request, 'login/index.html', locals())
        else:
            message_index = "上传失败"
            image_form = login_forms.UploadImageForm()
        return render(request, 'login/index.html', locals())
    else:
        image_form = login_forms.UploadImageForm()
        message = "请上传文件！"
        return render(request, 'login/index.html', locals())


def login(request):
    # 不允许重复登录
    if request.session.get('is_login', None):
        return redirect('/index/')
    if request.method == "POST":
        # username = request.POST.get('username')
        # password = request.POST.get('password')
        login_form = login_forms.UserForm(request.POST)
        message = '请检查填写的内容'
        # 数据验证
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')

            # 用户合法性判断
            try:
                # 数据查询API
                user = login_models.User.objects.get(name=username)
            except BaseException:
                message = '用户不存在！'
                # local()为python内置函数，返回当前所有的本地变量字典
                return render(request, 'login/login.html', locals())

            if user.password == hash_code(password):
                # session 字典中写入数据
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                return redirect('/index/')
        else:
            return render(request, 'login/login.html', locals())
    login_form = login_forms.UserForm()
    # 若不写locals() 则不能在login.html上调用{{ login_form }}
    return render(request, 'login/login.html', locals())


def register(request):
    if request.session.get('is_login', None):
        return redirect('/index/')
    if request.method == 'POST':
        register_form = login_forms.RegisterForm(request.POST)
        message = "请检查填写内容！"
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            password1 = register_form.cleaned_data.get('password1')
            password2 = register_form.cleaned_data.get('password2')
            email = register_form.cleaned_data.get('email')
            sex = register_form.cleaned_data.get('sex')
            if password1 != password2:
                message = "两次输入的密码不同！"
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = login_models.User.objects.filter(name=username).count()
                if same_name_user != 0:
                    message = '用户名已存在！'
                    return render(request, 'login/register.html', locals())
                same_email_user = login_models.User.objects.filter(email=email).count()
                if same_email_user != 0:
                    message = '邮箱已被注册！'
                    return render(request, 'login/register.html', locals())
                # 写入数据库
                new_user = login_models.User()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                return redirect('/login/')
        else:
            return render(request, 'login/register.html', locals())
    register_form = login_forms.RegisterForm()
    return render(request, 'login/register.html', locals())


@check_login
def logout(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    # 清除session数据
    request.session.flush()
    return redirect('/login')


@check_login
def rusult(request, uuid_code=''):
    if request.method == 'GET':
        context = dict()
        if uuid_code == '':
            pictures = login_models.Image.objects.all()
            context['images']=[]
            for picture in pictures:
                images=dict()
                images['username'] = picture.user_name
                images['image_path'] = picture.image.name
                images['uuid'] = picture.uuid
                context['images'].append(images)
            print(context['images'])
            return render(request, 'login/image_list.html', context)
        else:
            username = request.session['user_name']
            if login_models.Image.objects.filter(user_name=username, uuid=uuid_code).count() != 0:
                picture = login_models.Image.objects.get(user_name=username, uuid=uuid_code)
                context['image'] = '%s' % picture.image.name
                print(picture.content)
                context['results'] = [] if picture.content == '' else json.loads(picture.content)
            return render(request, 'login/result.html', context)
    elif request.method == 'POST':
        pass

    # try:
    #
    #     contex=somewhere.handle_uploaded_file(picture)
    # except:
    #     return HttpResponse("查询失败")
    # else:
    #     return render(request, 'login/result.html', {'context':contex})
